<template>
  <!-- 总计划编辑 -->
  <div class="e-form">
    <div class="tabs" v-if="Object.keys(basicFormData).length != 0" warningTabs>
      <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
        <!-- 基本信息 -->
        <el-tab-pane
          label="基本信息"
          name="baseInfo"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="物资明细"
          name="goodsAndMaterials"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <el-tab-pane
          label="附件信息"
          name="accessory"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="审核历史"
          name="auditHistory"
          :disabled="clickTabFlag"
        ></el-tab-pane>
        <el-tab-pane
          label="变更历史"
          name="alteration"
          :disabled="clickTabFlag"
        ></el-tab-pane>

        <div>
          <!-- 基本信息 -->
          <div id="baseInfoCon" class="con">
            <div class="e-form">
                 <BillTop title="总计划编辑" @cancel="handleClose"></BillTop>
              <div class="tabs">
                <div class="tabs-title" id="baseInfo">基本信息</div>
                <div style="width: 100%" class="form">
                  <el-form
                    :model="basicFormData"
                    label-width="150px"
                     ref="ruleForm"
                    :rules="rules"
                    class="demo-ruleForm"
                  >
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="总计划编号">
                          {{basicFormData.billNo}}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="单据机构">
                          {{ basicFormData.orgName }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="采购方式" prop="purchaseType">
                          <el-radio-group v-model="basicFormData.purchaseType">
                            <el-radio :label="0">普通采购</el-radio>
                            <el-radio :label="1">集中采购</el-radio>
                          </el-radio-group>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="计划日期" prop="planDate">
                          <el-date-picker
                            v-model="basicFormData.planDate"
                            type="date"
                            placeholder="选择日期"
                            :clearable="false"
                            value-format="yyyy-MM-dd"
                          >
                          </el-date-picker>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item
                          label="不含税计划金额(元)"
                          v-model="basicFormData.amount"
                        >
                          <!-- 汇总物资明细市场金额，保留两位小数，不可修改 -->
                          {{ basicFormData.amount.toFixed(2) }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="税率%" prop="taxRate">
                          <el-input
                            @input="taxRateinput"
                            @blur="countTaxAmount"
                            placeholder="请填写"
                            v-model="basicFormData.taxRate"
                            clearable
                             v-enter-float="{
                                    set: this,
                                    val: 'basicFormData',
                                    key: 'taxRate'
                                }"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item
                          label="计划金额(元)"
                          v-model="basicFormData.totalAmount"
                        >
                          <!-- 数字框，保留2位小数，不含税计划金额+税额。  -->
                          {{ basicFormData.totalAmount }}
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="税额" prop="taxAmount">
                          <!-- 默认计算：汇总（取清单市场金额*税率），允许修改，若修改则以修改值为准。 -->
                            <el-input
                            placeholder="请填写"
                            v-model="basicFormData.taxAmount"
                            clearable
                             v-enter-float="{
                                    set: this,
                                    val: 'basicFormData',
                                    key: 'taxAmount'
                                }"
                          ></el-input>
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="币种：" prop="currency">
                          <el-select
                            v-model="basicFormData.currencyId"
                            placeholder="请选择"
                            @change="currencyChange"
                          >
                            <el-option
                              v-for="item in currencyForm"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            >
                            </el-option>
                          </el-select>
                        </el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item
                          label="状态"
                          v-model="basicFormData.state"
                        >
                          {{
                            ["草稿", "审核中", "已审核", "已关闭", '',"已作废"][
                              basicFormData.state
                            ]
                          }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-form-item label="备注">
                        <el-input
                          type="textarea"
                          :rows="2"
                          placeholder="请输入内容"
                          v-model="basicFormData.remarks"
                        >
                        </el-input>
                      </el-form-item>
                    </el-row>

                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="填报人">{{
                          basicFormData.preparer
                        }}</el-form-item>
                      </el-col>
                      <el-col :span="12">
                        <el-form-item label="本位币">
                          {{ basicFormData.baseCurName }}
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col :span="12">
                        <el-form-item label="本位币汇率：">
                          <span v-if="basicFormData.baseCurRate === 1">  {{ basicFormData.baseCurRate }}</span>
                          <span v-else>
                            <el-input
                              placeholder="请输入本位币汇率"
                              v-model="basicFormData.baseCurRate"
                            >
                            </el-input>
                              </span>
                          </el-form-item>
                        <!-- 单据金额 * 本位币汇率 -->
                        <!-- <el-form-item label="计划金额（本位币）">
                          {{ basicFormData.baseCurAmount }}
                        </el-form-item> -->
                      </el-col>
                      <el-col :span="12">
                      <el-form-item label="人民币汇率：">
                        <span>{{ basicFormData.rmbRate }}</span>
                        </el-form-item>
                    </el-col>
                    </el-row>
                    <el-row>

                        </el-row>
                  </el-form>
                </div>
              </div>
            </div>

            <!-- ------------------------------------------------------------------------------------- -->
          </div>

          <!-- 物资明细 -->
          <div id="goodsAndMaterialsCon" class="con">
            <div class="tabs-title" id="goodsAndMaterials">物资明细</div>
            <div class="e-table">
              <div class="top">
                <div class="left">
                  <div>
                    <el-button
                      size="small"
                      style="background: rgb(75, 178, 255); color: #fff"
                      @click="selectEquip()"
                      >基础库引入</el-button
                    >
                    <el-button
                      size="small"
                      style="background: rgb(75, 178, 255); color: #fff"
                      @click="projectPlan()"
                      >工程计划引入</el-button
                    >
                  </div>

                </div>
              </div>
                <div class="errorMsg" v-if="errorMsg.length > 0">
                    <span v-for="(item, index) in errorMsg" :key="index">
                    {{ item }}
                    </span>
                </div>
              <el-table
                :data="goodsAndMaterialsList"
                border
                style="width: 100%"
                @selection-change="planTableSelect"
                :row-class-name="tableRowClassName"
                :cell-class-name="cellClsNm"
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                :tree-props="{
                  children: 'children',
                  hasChildren: 'hasChildren',
                }"
                row-key="uuid"
                :max-height="$store.state.tableHeight"
                 ref="table"
                v-sortTable="{ 'tableData': goodsAndMaterialsList, '_this': this, 'ref': 'table' }"
              >
                <el-table-column
                  label="操作"
                  fixed
                  width="100px"
                  align="left"
                  v-if="isDel"
                >
                  <template slot-scope="{ row, $index }">
                    <i
                      class="el-icon-delete"
                      style="cursor: pointer; font-size: 20px; color: red"

                      @click="deleteEle(row)"
                      v-if="$index > 0"
                    ></i>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="materialClassName"
                  label="类别"
                  min-width="200"
                  align="left"
                >
                  <!-- <template slot-scope="{ row }">
                        {{ row.topClassId ? row.materialClassName : (!row.customId.includes('-') ? row.materialClassName : '') }}
                    </template> -->
                </el-table-column>
                <el-table-column
                  prop="materialName"
                  label="物资名称"
                  width="100"
                >
                </el-table-column>
                <el-table-column prop="spec" label="规格型号" width="100">
                </el-table-column>
                <el-table-column prop="unit" label="计量单位" width="100">
                </el-table-column>
                <el-table-column prop="texture" label="材质" width="150">
                  <template slot-scope="{ row, $index }">
                    <el-input
                      @input="input(row)"
                      v-model="row.texture"
                      clearable
                      v-if="$index > 0"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="planQuantity"
                  label="计划数量"
                  width="150"
                >
                  <!-- 1、带入工程物资理论计划中设计数量，可修改，不能超过设计数量，保留4位小数
                        从基础库引入的物资，数量直接填写，保留4位小数 -->
                  <template slot-scope="{ row, $index }">
                    <el-input
                    v-enter-float2="{
                          set: row,
                          key: 'planQuantity'
                      }"
                      @input="input(row)"
                      v-model="row.planQuantity"
                      @blur="countMarketAmount"
                      clearable
                      v-if="$index > 0"
                    ></el-input>
                    <!-- <span class="totoal" v-if="$index > 0 && basicFormData.state === '2' && row.planQuantity">已汇总</span>
                    <span class="totoal" v-if="$index > 0 && basicFormData.state === '2' && !row.planQuantity || row.planQuantity===0">已汇总</span> -->
                  </template>
                </el-table-column>
                <el-table-column
                  prop="designQuantity"
                  label="设计数量"
                  width="130"
                >
                </el-table-column>
                <el-table-column
                  prop="budgetPrice"
                  label="预算单价（元）"
                  width="130"
                >
                </el-table-column>
                <el-table-column
                  prop="budgetAmount"
                  label="预算金额（元）"
                  width="130"
                >
                  <!-- 系统计算，计划数量*预算单价，不可编辑，保留两位小数 -->
                </el-table-column>
                <el-table-column
                  prop="marketPrice"
                  label="市场单价(元)"
                  width="130"
                >
                 <template slot-scope="{ row, $index }">
                    <el-input
                    v-enter-float="{
                          set: row,
                          key: 'marketPrice'
                      }"
                      @input="input(row)"
                      v-model="row.marketPrice"
                       @blur="countMarketAmount"
                      clearable
                      v-if="$index > 0"
                    ></el-input>
                  </template>
                </el-table-column>
                <el-table-column
                  prop="marketAmount"
                  label="市场金额（元）"
                  width="130"
                >
                  <!-- 系统默认计算，即计划数量*市场单价，不可编辑，金额累计保留2位小数，采用四舍五入方式。 -->
                </el-table-column>
                <el-table-column
                  prop="purchasingUnitName"
                  width="150"
                >
                  <template  slot="header">
                    <span>采购单位</span>
                    <i slot="suffix" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;" @click="selectPurchasingUnitName()"></i>
                  </template>
                  <template slot-scope="{ row,$index  }">
                  <el-input
                    @input="input(row)"
                    v-model="row.purchasingUnitName"
                      v-if="$index > 0"
                  >
                  <i slot="suffix" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;" @click="selectPurchasingUnitNames(row)"></i>
                  </el-input>
                </template>
                  <!-- 录入人可选择，审核中由审核人核准数据为准，单选，弹窗选择组织机构数据。 -->
                </el-table-column>
                <el-table-column
                  prop="purchaseType"
                  label="采购方式"
                  width="150"
                   v-if="basicFormData.purchaseType === 0"
                >
                  <!-- 录入人可选择，审核中由审核人核准数据为准，单选 -->
                   <template  slot="header">
                    <span>采购方式</span>
                    <i slot="采购方式" class="el-input__icon el-icon-document-copy" style=" cursor: pointer;" @click="selectPurchaseType()"></i>
                  </template>
                  <template slot-scope="{ row,$index  }">
                      <el-select v-model="row.purchaseType" placeholder="请选择" v-if="$index > 0" @change="selectProcurementMethod(row)">
                          <el-option
                            v-for="item in procurementMethod"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                          </el-option>
                    </el-select>
                    </template>
                </el-table-column>
                 <!-- <el-table-column
                  prop="purchaseType"
                  label="采购方式"
                  width="150"
                   v-else
                >
                <template slot-scope="{ row  }">
                  <span>{{['邀请招标','公开招标','询价','竞争性谈判','单一性来源','甲控'][row.purchaseType]}}</span>
                </template>
                 </el-table-column> -->
              </el-table>
            </div>
          </div>
          <!-- 附件信息 -->
          <div id="accessoryCon" class="con">
            <div class="tabs-title" id="accessory">附件信息</div>
             <attach-comp
              :relationId="attachId"
              bucketName="material"
              v-if="objFlag.flag5"
              ref="attachComp"
            />
            <div class="seize-a-seat" v-else>
              <i class="el-icon-loading"></i>
            </div>
          </div>
          <!-- 审核历史 -->
           <div id="auditHistoryCon" class="con">
              <div class="tabs-title" id="auditHistory">审核历史</div>
              <div class="e-table">
                  <ComAuditHistoryIndex
                      :tableData.sync="auditHistoryTable"
                      @getAuditHistory="getAuditHistory"
                      ref="AuditHistoryRef"
                  />
              </div>
          </div>
          <!-- 变更历史 -->
          <div id="alterationCon" class="con">
            <div class="tabs-title" id="alteration">变更历史</div>
            <div class="e-table">
              <el-table
                :data="changeData"
                border
                style="width: 100%"
                :cell-class-name="cellClsNm"
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                 ref="table"
                v-sortTable="{ 'tableData': changeData, '_this': this, 'ref': 'table' }"
              >
                <el-table-column prop="period" label="变更期数" width="80">
                </el-table-column>
                <el-table-column prop="billNo" label="变更编号" min-width="400">

                </el-table-column>
                <el-table-column prop="planDate" label="变更时间" width="200">
                </el-table-column>
                <el-table-column
                  prop="amount"
                  label="原计划金额（元）"
                  width="200"
                >
                </el-table-column>
                <el-table-column
                  prop="amountChange"
                  label="变更金额（元）"
                  width="200"
                >
                </el-table-column>
                <el-table-column
                  prop="amountChanged"
                  label="变更后计划金额（元）"
                  width="200"
                >
                </el-table-column>
                <el-table-column prop="state" label="状态" width="200">
                  <template slot-scope="scope">
                    <span>
                      {{
                        ["草稿", "审核中", "已审核", "已关闭",'', "已作废"][
                          scope.row.state
                        ]
                      }}
                    </span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </div>
      </el-tabs>
    </div>
    <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    <div class="buttons">
      <span class="tip"
        ><span style="color: red; margin-right: 0">*</span>为必填项</span
      >
      <el-button
          type="primary"
          style="background: #2e61d7"
          v-debounce
          v-if="basicFormData.state === '1'"
          >打印</el-button
      >
       <ComExaButtons
                v-if="basicFormData.state != 5"
                :auditState="auditState"
                :state="basicFormData.state"
                 :founderId="founderId"
                @exas="exas"
            />

      <!-- <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        @click="save('basicFormData')"
        v-debounce
        >保存</el-button
      >
      <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        @click="submit"
        v-debounce
        >保存并提交</el-button
      >
       <el-button
        type="primary"
        size="small"
        style="background: #2e61d7"
        @click="undoAudit"
        v-if="basicFormData.state === '1'"
        v-debounce
        >撤回</el-button
      >
      <el-button
        type="primary"
        class="btn-delete"
        v-debounce
        v-if="basicFormData.state === '1'"
        @click="nullify()"
        >作废</el-button
          >

      <el-button
        type="danger"
        size="small"
        @click="ctDelete"
        v-if="basicFormData.state === '0'"
        v-debounce
        >删除</el-button
      > -->

      <el-button size="small" @click="handleClose">关闭</el-button>
    </div>
  </div>
</template>

<script>
import '@/utils/jquery.scrollTo.min'
import { mapMutations, mapState } from 'vuex'
import {  getUuid, selectDataClient, openAppClient  } from '@/utils/common'
import AttachComp from '@/components/common/attachIndex'
import { getRmbRate } from '@/api/equip/common.js'
import request from '@/api/materials/plan.js'
import $ from 'jquery'
import CommonApi from '@/api/materials/common.js'
import ComAuditHistoryIndex from '@/pages/materialsmanagement/components/auditHistory/auditHistoryIndex'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            userName: '',
            // selectData: false,
            form: {
                name: '',
                region: '',
                date1: '',
                date2: '',
                delivery: false,
                type: [],
                resource: '',
                desc: '',
            },
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],

            isErrorMsg: true, //是否提醒错误信息
            isBatch: true, //是否进入批量操作
            batch: '进入批量管理',
            tableData: [],
            changeData: [],
            goodsAndMaterialsList: [], //明细
            planSelect: [], //计划明细选择项
            auditHistoryTable: [], //审核历史
            value: '',
            textarea: '',
            formData: {},
            auditState: {},
            data: [], //
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            //基本信息表单数据
            basicFormData: {
                amount: 0,
                baseCurAmount: 0,
                baseCurId: '',
                baseCurName: '',
                baseCurRate: 0,
                baseCurTaxAmount: 0,
                baseCurTotalAmount: 0,
                billId: '',
                billNo: '',
                currency: '',
                currencyId: '',
                founderId: '',
                founderName: '',
                gmtCreate: '',
                gmtModified: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                planDate: '',
                preparer: '',
                preparerId: '',
                projectPlanId: '',
                purchaseType: 0,
                remarks: '',
                rmbAmount: 0,
                rmbId: '',
                rmbName: '',
                rmbRate: 0,
                rmbTaxAmount: 0,
                rmbTotalAmount: 0,
                state: '',
                taxAmount: 0,
                taxRate: 0,
                totalAmount: 0,
                workId: '',
            },
            objFlag: {
                flag5: false,
            },
            selectEquipVisible: false,
            moneyList: [], //币种
            orgId: '', //机构id
            orgName: '', //机构名称
            userId: '', //当前用户id
            billId: '',
            isSkip: false, //是否跳转
            hideen: false,
            dtlId1: '',
            dtlId2: '',
            isDel: true,
            designQuantitys: 0,
            auditParams: {
                billId: this.$route.query.billid, //单据Id  ***
                billType: '1001', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgId, //单据机构Id
                orgName: JSON.parse(localStorage.getItem('vuex')).userInfo.orgInfo.orgName, //单据机构名称
                userId: localStorage.getItem('userId'), //审核人Id    ***
                workId: '', //流程Id
            },
            nullifyParams: { //作废
                'billId': this.$route.query.billid,
                'billType': 1001,
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': ''
            },
            procurementMethod: [{
                value: 0,
                label: '邀请招标'
            }, {
                value: 1,
                label: '公开招标'
            }, {
                value: 2,
                label: '询价'
            }, {
                value: 3,
                label: '竞争性谈判'
            }, {
                value: 4,
                label: '单一性来源'
            },
            {
                value: 5,
                label: '甲控'
            }],
            //验证
            rules: {
                planDate: [
                    {
                        required: true,
                        message: '请选择计划日期',
                        trigger: 'change',
                    },
                ],
                taxRate: [{ required: true, message: '请填写税率', trigger: 'change' }],
                taxAmount: [{ required: true, message: '请填写税额', trigger: 'change' }],
                purchaseType: [
                    {
                        required: true,
                        message: '请至少选择一个采购方式',
                        trigger: 'change',
                    },
                ],
                currency: [
                    {
                        required: true,
                        message: '请至少选择一个币种',
                        trigger: 'change',
                    },
                ],
            },
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            options: state => state.contract.ctClassify,

        }),

        judgeRoute () {
            if (this.$route.path.includes('Add')) {
                return false
            }
            return true
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billid
        },
        purchaseType () {
            return this.goodsAndMaterialsList[0].children[0].purchaseType
        },

    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    components: {
        AttachComp,
        ComAuditHistoryIndex,
    // selectData,
    },
    created () {
        let data = JSON.parse(localStorage.getItem('vuex'))
        this.basicFormData.orgId = data.userInfo.orgInfo.orgId
        this.basicFormData.orgName = data.userInfo.orgInfo.orgName
        this.basicFormData.userId = localStorage.getItem('userId')
        this.userName = localStorage.getItem('userName')
        this.founderId = localStorage.getItem('userId')
        this.userId = localStorage.getItem('userId')
        this.billid = this.$route.query.billid
        this.getBasicData() //进入页面就获取基本信息数据
        this.getchangeData()
        this.getAttach()
        this.getMasterPlan() //明细数据
        this.getAuditHistory()
        this.getinfo()
        // this.totalTaxAmount()
        // setTimeout(()=>{
        //     console.log('a>>>>', this.goodsAndMaterialsList)

        //     this.goodsAndMaterialsList.forEach(a=>{
        //         a.children.forEach(b=>{
        //             console.log('b.materialClassName', b.materialClassName)
        //             console.log('b.spec', b.spec)
        //             console.log('b.texture', b.texture)

        //         })
        //     })
        // }, 500)
        this.getCurrentUnitInfo()

    },
    mounted () {
    // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = [
            'baseInfo',
            'goodsAndMaterials',
            'accessory',
            'auditHistory',
            'alteration',
        ]
        this.tabArr = arr //标星星
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const $item = document.getElementById(item)
                    let itemTop = null
                    if ($item) {
                        itemTop = $item.offsetTop
                    }
                    return itemTop
                })
            }
            const scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    methods: {
        ...mapMutations(['setSelectedInfo', 'setAuditParams']),
        // 获取按钮状态
        getCurrentUnitInfo () {
            CommonApi
                .getCurrentUnitInfo({
                    billId: this.$route.query.billid,
                    billType: 1001,
                    freeNextUnitIndex: 0,
                    freeNextUser: '',
                    isPass: true,
                    isShareInAudit: true,
                    opinion: ''
                })
                .then(res => {
                    this.auditState = res
                })
        },
        // 按钮组件触发事件
        exas (data) {
            switch (data) {
            case 'audit':
                this.audit() //审核
                break
            case 'undoAudit':
                this.undoAudit() //撤回
                break
            case 'submitCommit':
                this.submit() //提交
                break
            case 'submit':
                this.save() //保存
                break
            case 'nullify':
                this.nullify() //作废
                break
            case 'deleteData':
                this.ctDelete() //删除
                break
            default:
                break
            }
        },
        //作废
        nullify () {
            this.setAuditParams(this.nullifyParams)
            openAppClient('/nullifyDialog', '单据作废原因', () => {
                const auditParams = JSON.parse(localStorage.vuex).auditParams
                CommonApi.nullify(auditParams).then(() => {
                    this.clientPop('suc', '作废成功', this.handleClose, null, this.handleClose)
                })
            })
        },

        //判断税率是否大于100
        taxRateinput () {
            console.log('税率', this.basicFormData.taxRate)
            if(this.basicFormData.taxRate > 100) {
                this.basicFormData.taxRate = 0
            }
        },
        //计算明细的市场金额
        countMarketAmount () {
            let num = 0
            if(this.goodsAndMaterialsList.length === 0) {
                return
            }else{

                this.goodsAndMaterialsList.forEach(a=>{
                    a.children.forEach(b=>{
                        b.marketAmount = b.planQuantity * b.marketPrice
                        b.marketAmount = b.marketAmount.toFixed(2)
                        num += Number(b.marketAmount)
                        this.basicFormData.amount  = num
                        this.basicFormData.totalAmount = num
                        this.basicFormData.totalAmount = this.basicFormData.totalAmount.toFixed(2)
                        this.countTaxAmount()

                    })
                })
            }
        },

        //计算税额
        countTaxAmount () {
            let num = 0
            if(this.goodsAndMaterialsList.length !== 0) {

                this.goodsAndMaterialsList.forEach(a=>{
                    a.children.forEach(b=>{
                        b.marketAmount = b.planQuantity * b.marketPrice
                        b.marketAmount = b.marketAmount.toFixed(2)
                        num += Number(b.marketAmount)
                        this.basicFormData.taxAmount = (this.basicFormData.taxRate * num ) / 100
                        // this.basicFormData.taxAmount = (this.basicFormData.taxRate * num )
                        this.basicFormData.taxAmount = this.basicFormData.taxAmount.toFixed(2)
                        //计算  计划金额（元）  不含税计划金额+税额
                        this.basicFormData.totalAmount = num + Number(this.basicFormData.taxAmount)

                        this.basicFormData.totalAmount = this.basicFormData.totalAmount.toFixed(2)

                    })
                })
            }
        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //采购单位  批量选择
        selectPurchasingUnitName () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/hr/org/getAllOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择机构' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)
                    //         openAppClient('/showSelectedData', '选择结果', function () {
                    //             // alert('关闭后回调')
                    //         })
                    // let val = [{ 'orgId': '1439990096949411840', 'orgName': '贵州江习古高速公路开发有限公司', 'shortCode': 'JSGS', 'orgType': '2', 'parentId': 'ad551eff9d03-8efe-2148-9ed8-64781e1e', 'parentName': '四川路桥建设集团股份有限公司' }]
                    val.forEach(b=>{
                        this.goodsAndMaterialsList.forEach(item=>{
                            item.children.forEach(a=>{
                                if(a.changeType === 1) {
                                    a.changeType = 1
                                }else{
                                    a.changeType = 2
                                }
                                a.purchasingUnitId = b.orgId
                                a.purchasingUnitName = b.orgName
                            })
                        })
                    })

                })

        },
        //采购单位  单个选择
        selectPurchasingUnitNames (row) {
            console.log('row', row)
            let ids = []
            selectDataClient({
                SelectServiceToken: '/hr/org/getAllOrgPage', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                Title: '选择机构' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)
                    val.forEach(item=>{
                        if(item.changeType === 1) {
                            item.changeType = 1
                        }else{
                            item.changeType = 2
                        }
                        row.purchasingUnitId = item.orgId
                        row.purchasingUnitName = item.orgName
                        this.goodsAndMaterialsList.forEach(a=>{
                            if(a.changeType === 1) {
                                a.changeType = 1
                            }else{
                                a.changeType = 2
                            }
                            a.children.forEach(b=>{
                                b.children.forEach(c=>{
                                    if(row.dtlId === c.dtlId) {
                                        c.changeType = 2
                                        c.purchasingUnitId = item.orgId
                                        c.purchasingUnitName = item.orgName
                                    }
                                })
                            })
                        })
                    })
                })

        },
        //选择采购方式
        selectProcurementMethod (row) {
            console.log('row0', row)
            this.goodsAndMaterialsList.forEach(item=>{
                item.children.forEach(a=>{
                    if(row.dtlId === a.dtlId) {
                        if(a.changeType === 1) {
                            a.changeType = 1
                        }else{
                            a.changeType = 2
                        }

                    }else if(a.changeType !== 2) {
                        a.changeType = 0
                    }
                })
            })
        },
        //选择采购方式  批量
        selectPurchaseType () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/config/kv/getDicValue', // 客户端对应方法名
                IsSingleMode: true, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    type: 1,
                    dicName: '总计划明细采购方式',
                    dicKey: '',
                }),
                Title: '选择采购方式' // 标题
            })
                .then(val=>{
                    this.setSelectedInfo(val)
                    val.forEach(b=>{
                        this.goodsAndMaterialsList.forEach(item=>{
                            item.children.forEach(a=>{
                                if(a.changeType === 1) {
                                    a.changeType = 1
                                }else{
                                    a.changeType = 2
                                }
                                a.purchaseType = b.kvValue
                                if(a.purchaseType == 0) {
                                    a.purchaseType = '邀请招标'
                                }
                                if(a.purchaseType == 1) {
                                    a.purchaseType = '公开招标'
                                }
                                if(a.purchaseType == 2) {
                                    a.purchaseType = '询价'
                                }
                                if(a.purchaseType == 3) {
                                    a.purchaseType = '竞争性谈判'
                                }
                                if(a.purchaseType == 4) {
                                    a.purchaseType = '单一性来源'
                                }
                                if(a.purchaseType == 5) {
                                    a.purchaseType = '甲控'
                                }
                            })
                        })
                    })
                })
        },
        //转换采购方式匹配后端所需的格式
        purchaseTypes () {
            this.goodsAndMaterialsList.forEach(item=>{
                item.children.forEach(a=>{
                    if(a.purchaseType === '邀请招标') {
                        a.purchaseType = 0
                    }else if(a.purchaseType === '公开招标') {
                        a.purchaseType = 1
                    }else if(a.purchaseType === '询价') {
                        a.purchaseType = 2
                    }else if(a.purchaseType === '竞争性谈判') {
                        a.purchaseType = 3
                    }else if(a.purchaseType === '单一性来源') {
                        a.purchaseType = 4
                    }else if(a.purchaseType === '甲控') {
                        a.purchaseType = 5
                    }
                })
            })
        },
        //汇总汇总税额
        totalTaxAmount () {
            this.basicFormData.taxAmount =
        (this.basicFormData.amount * this.basicFormData.taxRate).toFixed(2)
            this.totalAmount()
        },
        //汇总计划金额(元)
        totalAmount () {
            this.basicFormData.totalAmount =
               ( Number(this.basicFormData.amount) + Number(this.basicFormData.taxAmount)).toFixed(2)

        },
        //计算 计划金额(本位币)
        baseCurAmount () {
            this.basicFormData.baseCurAmount =
        this.basicFormData.amount * this.basicFormData.baseCurRate
        },
        //批量管理
        batchOperation () {
            this.isBatch = !this.isBatch
            if (this.isBatch) {
                this.batch = '退出批量管理'
                // this.$refs.table.clearSelection()
            } else {
                this.batch = '进入批量管理'
            }
        },
        getinfo () {
            const { baseCyByOrgId } = this.userInfo
            this.basicFormData.baseCurName = baseCyByOrgId.currencyName //本位币
            this.basicFormData.baseCurId = baseCyByOrgId.currency
        },
        //币种切换
        currencyChange (val) {
            this.basicFormData.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种

            getRmbRate({
                //获取机构下某币种的人民币汇率
                currency: val,
                orgId: this.userInfo.orgInfo.orgId,
            })
                .then(res => {
                    console.log('res', res)
                    this.basicFormData.rmbId = res.rateId
                    this.basicFormData.rmbName = res.rate
                    this.basicFormData.rmbRate = res.rate
                    if (res.rate === 1) {
                        this.basicFormData.rmbRate = res.rate
                        this.basicFormData.rmbId = res.currency
                    } else {
                        this.basicFormData.rmbRate = res.rate
                        this.basicFormData.rmbId = res.rateId
                    }
                })
                .catch(() => {})

            if (this.basicFormData.currencyId === this.basicFormData.baseCurId) {
                //币种=本位币
                this.basicFormData.baseCurRate = 1
                this.showBaseCurName = false
            } else {
                this.basicFormData.baseCurRate = null
                this.showBaseCurName = true
            }
        },

        //基础库引入按钮
        selectEquip () {
            let ids = []
            selectDataClient({
                SelectServiceToken: '/material/categoryLibrary/queryListByParentClassId2',
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: ids, // 已选中id
                InitParamsStr: JSON.stringify( this.basicFormData.purchaseType === 0 ? { 'parentiId': 0, 'topClassNameNeed': ['主要材料'], 'isCentralizedPurchasing': 0 } : { 'parentiId': 0, 'topClassNameNeed': ['主要材料'], }),
                Title: '物料选择'
            })
            // let val = [{ 'billId': '001a45e7-b355-4f63-b773-e08243762044', 'billNo': 'L.01.02.003.012', 'classId': '5b8670ea-a890-4b20-8724-8c51239989a5', 'classIdPath': 'a927247cb7b1-980c-724d-300a-7fdc7a5b/a92724c24cd4-989d-0646-1070-2b007ca9/5b8670ea-a890-4b20-8724-8c51239989a5', 'className': '无缝钢管', 'classNamePath': '主要材料/其它钢材/无缝钢管', 'materialName': '无缝钢管', 'spec': 'Ф60mm', 'unit': 't' }, { 'billId': '003698cd-8043-4166-8a40-21681cd46977', 'billNo': 'L.01.18.003.080', 'classId': '10b6ca0d-7dc8-4052-8388-12b73b16d6c8', 'classIdPath': 'a927247cb7b1-980c-724d-300a-7fdc7a5b/95505537-1ea0-4677-a571-83b606c0a208/10b6ca0d-7dc8-4052-8388-12b73b16d6c8', 'className': '钢护栏', 'classNamePath': '主要材料/钢结构加工品/钢护栏', 'materialName': '配套件', 'spec': '横隔梁', 'unit': '个' }]
                .then(val => {
                    this.setSelectedInfo(val)
                    //     openAppClient('/showSelectedData', '选择结果', function () {
                    //         // alert('关闭后回调')
                    //     })
                    if(this.goodsAndMaterialsList.length > 0) {
                        val.forEach(e=>{
                            this.goodsAndMaterialsList.forEach(a=>{
                                const  Isrepeat =  a.children.some(b=>{
                                    return b.materialName == e.materialName && b.spec == e.spec && b.texture == ''
                                })
                                if(Isrepeat) {
                                    console.log('e.materialClassName', e)
                                    this.clientPop('info', `物资明细不允许重复,物资类别:${e.classNamePath},物资名称:${e.materialName},规格:${e.spec},请检查!`)
                                }else{
                                    e.materialClassNameArr = e.classNamePath.split('/')
                                    e.materialClassIdArr = e.classIdPath.split('/')
                                    e.materialClassNameArr.shift()
                                    e.materialClassIdArr.shift()
                                    console.log('e', e)
                                    const obj = {
                                        uuid: getUuid(),
                                        billId: this.billid,
                                        billNo: this.basicFormData.billNo,
                                        budgetAmount: 0, //预算金额(元)
                                        budgetPrice: 0, //预算单价(元)
                                        changeType: 1,
                                        designQuantity: 0, //设计数量
                                        dtlId: '', //物资总计划明细id
                                        marketAmount: 0, //市场金额(元)
                                        marketPrice: 0, //市场单价(元)
                                        customId: getUuid(),
                                        materialClassId: e.materialClassIdArr.join('/'), //物资类别id(
                                        materialClassName: e.materialClassNameArr.join('/'), //物资类别名称
                                        materialId: e.billId, //物资id
                                        materialName: e.materialName, //物资名称
                                        planQuantity: 0, //计划数量
                                        projectPlanDtlId: '', //工程计划明细id
                                        purchaseType: null, //采购方式
                                        purchasingUnitId: '', //采购单位id
                                        purchasingUnitName: '', //采购单位名称
                                        spec: e.spec, //规格型号
                                        texture: e.texture, //材质
                                        unit: e.unit, //计量单位
                                    }
                                    a.children.push(obj)
                                }
                            })
                        })
                    }else{
                        const mapObj = {}
                        let arr = []
                        val.forEach(e => {
                            const children = []
                            e.materialClassNameArr = e.classNamePath.split('/')
                            e.materialClassIdArr = e.classIdPath.split('/')
                            // TODO: 统计小计
                            let obj
                            const topClassId = e.materialClassIdArr.splice(0, 1).toString()
                            const topClassName = e.materialClassNameArr.splice(0, 1).toString()
                            if (!mapObj[topClassId]) {
                                obj = {
                                    topClassId,
                                    topClassName,
                                    customId: topClassId,
                                    materialClassId: topClassId,
                                    materialClassName: topClassName,
                                    uuid: getUuid(),
                                    totalAmount: '',
                                    totalQuantity: '',
                                }
                                //这里需要改成push多个对象   还没改
                                arr.push(obj)

                                mapObj[topClassId] = obj
                            } else {
                                obj = mapObj[topClassId]
                            }

                            // 物资名称
                            children.push({
                                uuid: getUuid(),
                                billId: this.billid,
                                billNo: this.basicFormData.billNo,
                                budgetAmount: 0, //预算金额(元)
                                budgetPrice: 0, //预算单价(元)
                                changeType: 1,
                                designQuantity: 0, //设计数量
                                dtlId: '', //物资总计划明细id
                                marketAmount: 0, //市场金额(元)
                                marketPrice: 0, //市场单价(元)
                                customId: getUuid(),
                                materialClassId: e.materialClassIdArr.join('/'), //物资类别id(
                                materialClassName: e.materialClassNameArr.join('/'), //物资类别名称
                                materialId: e.billId, //物资id
                                materialName: e.materialName, //物资名称
                                planQuantity: 0, //计划数量
                                projectPlanDtlId: '', //工程计划明细id
                                purchaseType: null, //采购方式
                                purchasingUnitId: '', //采购单位id
                                purchasingUnitName: '', //采购单位名称
                                spec: e.spec, //规格型号
                                texture: e.texture, //材质
                                unit: e.unit, //计量单位
                            })
                            obj.children = !obj.children
                                ? children
                                : obj.children.concat(children)
                            // 统计小计
                            const count = obj.children.reduce(
                                (prev, c) => (prev += c.marketAmount || 0),
                                0
                            )
                            obj.materialName = `小计： ${count.toFixed(2)}`
                            obj.children = this.uniqueArray(obj.children, 'customId')
                        })
                        this.goodsAndMaterialsList = arr
                    }

                    this.countMarketAmount()
                    // this.collectCount()
                    //this.totalAmount()
                })

        },
        //判断物资是否全部一样
        Isrepeat () {
            this.goodsAndMaterialsList.forEach(a=>{
                if(a.children.every(item=>item.materialId === a.children[0].materialId && item.spec === a.children[0].spec && item.texture === a.children[0].texture)) {
                    this.clientPop('info', '物资明细不允许重复,请检查!')
                }else{
                    console.log('不相同')
                }
            })
        },
        count_ (obj) {
            return obj.children.reduce((prev, c) => (prev += c.amount || 0), 0)
        },
        //工程计划引入
        projectPlan () {
            this.$Ajax
                .httpPost({
                    url: '/project/mtp/getMaterialPlanDtlPage',
                    params: {
                        'codeList': [],
                        'limit': 10,
                        'materialList': [],
                        'page': 1,
                        'structureList': []
                    },
                })
                .then(val=>{
                    if(val.list.length == 0 || val.list.length == null) {
                        this.clientPop('info', '暂无数据!')
                    }else{
                        this.goodsAndMaterialsList = []
                        const mapObj = {}
                        let arr = []
                        let num = 0
                        val.list.forEach(item => {
                            const children = []
                            item.materialClassNameArr = item.materialClassName.split('/')
                            item.materialClassIdArr = item.materialClassId.split('/')
                            num = item.totalQty
                            // TODO: 统计小计
                            let obj
                            const topClassId = item.materialClassIdArr.splice(0, 1).toString()
                            const topClassName = item.materialClassNameArr
                                .splice(0, 1)
                                .toString()
                            if (!mapObj[topClassId]) {
                                obj = {
                                    topClassId,
                                    topClassName,
                                    customId: topClassId,
                                    materialClassId: topClassId,
                                    materialClassName: topClassName,
                                    uuid: getUuid(),
                                    totalAmount: '',
                                    totalQuantity: '',
                                }
                                arr.push(obj)
                                mapObj[topClassId] = obj
                            } else {
                                obj = mapObj[topClassId]
                            }
                            // 物资名称
                            children.push({
                                uuid: getUuid(),
                                billId: this.billid,
                                billNo: this.basicFormData.billNo,
                                budgetAmount: 0, //预算金额(元)
                                budgetPrice: 0, //预算单价(元)
                                changeType: 1,
                                designQuantity: item.totalQty, //设计数量
                                dtlId: '', //物资总计划明细id
                                marketAmount: 0, //市场金额(元)
                                marketPrice: 0, //市场单价(元)
                                customId: getUuid(),
                                materialClassId: item.materialClassIdArr.join('/'), //物资类别id(
                                materialClassName: item.materialClassNameArr.join('/'), //物资类别名称
                                materialId: item.billId, //物资id
                                materialName: item.materialName, //物资名称
                                planQuantity: item.totalQty, //计划数量
                                projectPlanDtlId: '', //工程计划明细id    //绑   回来的dtid
                                purchaseType: null, //采购方式
                                purchasingUnitId: '', //采购单位id
                                purchasingUnitName: '', //采购单位名称
                                spec: item.spec, //规格型号
                                texture: item.texture, //材质
                                unit: item.unit, //计量单位
                            })
                            obj.children = !obj.children
                                ? children
                                : obj.children.concat(children)
                                // 统计小计
                            const count = obj.children.reduce(
                                (prev, c) => (prev += c.marketAmount || 0),
                                0
                            )
                            obj.materialName = `小计： ${count.toFixed(2)}`
                            obj.children = this.uniqueArray(obj.children, 'customId')
                        })
                        this.isDel = false
                        this.designQuantitys = num
                        this.goodsAndMaterialsList = arr
                    }
                    //this.collectCount()
                    // this.totalAmount()

                })

        },
        //明细数据汇总方法
        uniqueArray (arr, key) {
            const map = new Map()
            return arr.filter(item => {
                const val = item[key] + '' || getUuid()
                return !map.has(val) && map.set(val, 1)
            })
        },
        //取明细的市场金额向上汇总到基础表单 不含税计划金额(元)
        collectCount () {
            this.basicFormData.amount = 0
            this.goodsAndMaterialsList.forEach(v => {
                v.children.forEach(item => {
                    if (v.changeType != -1) {
                        this.basicFormData.amount += item.marketAmount
                    }
                })

            })
        },

        tableRowClassName ({ row }) {
            if (row.changeType === -1) {
                return 'warning-row'
            }
            return ''
        },
        ...mapMutations(['setPopConfirm']),
        //查询附件信息
        getAttach () {
            this.objFlag.flag5 = true
        },

        //获取基本信息数据
        getBasicData () {
            this.$Ajax
                .httpGet({
                    url: '/material/masterPlan/findById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    this.basicFormData = res
                    this.countMarketAmount()
                    this.countTaxAmount()
                })
        },
        //获取明细数据
        getMasterPlan () {
            this.$Ajax
                .httpGet({
                    url: '/material/masterPlan/getListById',
                    params: {
                        id: this.billid,
                    },
                })
                .then(res => {
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()
                        item.children.forEach(i => {
                            i.uuid = i.dtlId
                        })
                        const count = item.children.reduce(
                            (prev, c) => (prev += c.marketAmount || 0),
                            0
                        )
                        item.materialName = `小计： ${count.toFixed(2)}`
                    })
                    this.goodsAndMaterialsList = res
                    //this.collectCount()
                    // this.totalAmount()
                    this.countMarketAmount()
                    this.countTaxAmount()
                    console.log('this.goodsAndMaterialsList', this.goodsAndMaterialsList)

                })
        },
        //获取变更历史列表数据
        getchangeData () {
            this.$Ajax
                .httpPost({
                    url: '/material/masterPlanChanged/listByEntity',
                    params: {
                        limit: 10,
                        masterPlanBillId: this.billid,
                        page: 1,
                    },
                })
                .then(res => {
                    this.changeData = res.list
                })
        },
        //获取历史审核列表
        getAuditHistory () {
            const params = {
                billId: this.billid,
                billType: '1001',
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: '',
                orgId: '',
                orgName: '',
                userId: '',
                workId: ''
            }
            request.getAuditHistory(params).then(res => {
                this.auditHistoryTable = res
            })
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('evaluateCon')) {
                    const lastConHeight =
            document.getElementById('evaluateCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    console.log('this.lastConHeight', this.lastConHeight)
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        ctDelete () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        //删除
        delData () {
            this.$Ajax
                .httpGet({
                    url: '/material/masterPlan/delete',
                    params: {
                        id: this.billid,
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                })
                .then(res => {
                    if (res.code == 200) {
                        this.clientPop('suc', '删除成功', this.handleClose, null, this.handleClose)
                    }
                })
        },
        //

        //监听明细数据input事件
        input (row) {
            if(row.changeType === 1) {
                row.changeType = 1
            }else{
                row.changeType = 2
            }
            if(row.designQuantity !== 0) {
                if(row.planQuantity > row.designQuantity) {
                    this.clientPop(
                        'err',
                        '计划数量不能超过设计数量!',
                    )
                    setTimeout(()=>{
                        row.planQuantity = row.designQuantity
                    })
                }
            }

        },
        //验证附件
        isattachCon () {
            this.goodsAndMaterialsList.forEach(a=>{
                const attachCon =  a.children.some(item=>{
                    return item.purchaseType == 5
                })
                if(attachCon && this.$refs.attachComp.attachTableData.length === 0) {
                    this.clientPop('err', '物资采购方式为甲控时,请上传附件')
                }
            })
        },

        //保存
        save () {
            this.purchaseTypes()
            if(this.goodsAndMaterialsList.length == 0) {
                this.errorList = []
                Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                    .then(() => {
                        this.clientPop('suc', '保存成功', this.$router.go(0))
                    })
                    .catch(() => {
                        this.scorllError()
                    })
            }else{
                this.errorList = []

                this.goodsAndMaterialsList.forEach(a=>{
                    //验证附件
                    const attachCon =  a.children.some(item=>{
                        return item.purchaseType == 5
                    })
                    if(attachCon && this.$refs.attachComp.attachTableData.length === 0) {
                        this.clientPop('err', '物资采购方式为甲控时,请上传附件')
                    }else{
                        if(a.children.length != 1) {
                            if(a.children.every(item=>item.materialId === a.children[0].materialId && item.spec === a.children[0].spec && item.texture === a.children[0].texture)) {
                                this.clientPop('info', '物资明细不允许重复,请检查!')
                            } else{
                                this.errorList = []
                                Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                                    .then(() => {
                                        this.clientPop('suc', '保存成功', this.$router.go(0))
                                    })
                                    .catch(() => {
                                        this.scorllError()
                                    })
                            }
                        }
                        else{
                            this.errorList = []
                            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                                .then(() => {
                                    this.clientPop('suc', '保存成功', this.$router.go(0))
                                })
                                .catch(() => {
                                    this.scorllError()
                                })
                        }
                    }
                })
            }

        },
        //保存并提交
        submit () {
            this.purchaseTypes()
            if(this.goodsAndMaterialsList.length == 0) {
                this.verifyTable()
                this.errorList = []
                Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                    .then(() => {
                        request.AuditCommit(this.auditParams).then(() => {
                            this.clientPop('suc', '保存并提交成功', this.handleClose, null, this.handleClose)
                        })
                    })
                    .catch(() => {
                        this.scorllError()
                    })
            }else{
                this.errorList = []
                this.verifyTable()
                this.goodsAndMaterialsList.forEach(a=>{
                    //验证附件
                    const attachCon =  a.children.some(item=>{
                        return item.purchaseType == 5
                    })
                    if(attachCon && this.$refs.attachComp.attachTableData.length === 0) {
                        this.clientPop('err', '物资采购方式为甲控时,请上传附件')
                    }else{
                        if(a.children.length != 1) {
                            if(a.children.every(item=>item.materialId === a.children[0].materialId && item.spec === a.children[0].spec && item.texture === a.children[0].texture)) {
                                this.clientPop('info', '物资明细不允许重复,请检查!')
                            }else{
                                this.errorList = []
                                Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                                    .then(() => {
                                        request.AuditCommit(this.auditParams).then(() => {
                                            this.clientPop('suc', '保存并提交成功', this.handleClose, null, this.handleClose)
                                        })
                                    })
                                    .catch(() => {
                                        this.scorllError()
                                    })
                            }
                        }else{
                            this.errorList = []
                            Promise.all([this.updateBaseInfo(), this.updateBudgetDtl()])
                                .then(() => {
                                    request.AuditCommit(this.auditParams).then(() => {
                                        this.clientPop('suc', '保存并提交成功', this.handleClose, null, this.handleClose)
                                    })
                                })
                                .catch(() => {
                                    this.scorllError()
                                })
                        }

                    }

                })
            }

        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        request.updatebasicDataPlan(this.basicFormData)
                            .then(() => {
                                resolve()
                            })
                            .catch(err => {
                                this.setError('baseInfo')
                                reject(err)
                            })
                    } else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新计划明细
        updateBudgetDtl () {
            return new Promise((resolve, reject) => {
                this.verifyTable()
                    .then(() => {
                        request.updateMasterPlan(this.goodsAndMaterialsList)
                            .then(() => {
                                resolve()
                            })
                            .catch(err => {
                                this.setError('goodsAndMaterials')
                                reject(err)
                            })
                    })
                    .catch(err => {
                        this.setError('goodsAndMaterials')
                        reject(err)
                    })
            })
        },

        //明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                if (this.goodsAndMaterialsList.length > 0) {
                    this.goodsAndMaterialsList.forEach(v => {
                        v.children.forEach((item, index) => {
                            if (item.changeType !== -1) {
                                if (item.planQuantity == '' || item.planQuantity == null || item.planQuantity == 0) {
                                    let str = `请填写第 ${index + 1} 行的计划数量`
                                    this.errorMsg.push(str)
                                }
                                if (item.marketPrice == '' || item.marketPrice == null || item.marketPrice == 0) {
                                    let str = `请填写第 ${index + 1} 行的市场单价`
                                    this.errorMsg.push(str)
                                }
                                if(this.basicFormData.purchaseType == 1) {
                                    if (item.purchasingUnitName == '' || item.purchasingUnitName == null) {
                                        let str = `请选择第 ${index + 1} 行的采购单位`
                                        this.errorMsg.push(str)
                                    }
                                }
                                if(this.basicFormData.purchaseType == 0) {
                                    if (item.purchaseType === '' || item.purchaseType === null) {
                                        let str = `请选择第 ${index + 1} 行的采购方式`
                                        this.errorMsg.push(str)
                                    }
                                }

                            }
                        })
                    })
                }else{
                    let str = '物资明细不能为空!'
                    this.errorMsg.push(str)
                }

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }
            })
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },

        //撤回
        undoAudit () {
            const params2 = {
                billId: this.billid, //单据Id  ***
                billType: '1001', //单据编码  ***
                dtls: [], //审核中字段值变更历史
                freeNextUnitIndex: 0, //下一步审核步骤
                freeNextUser: '', //下一步审核人ID
                isPass: true, //审核是否通过
                isShareInAudit: true, //是否共享审核节点
                opinion: '', //审核意见   ***
                orgId: '', //单据机构Id
                orgName: '', //单据机构名称
                userId: this.userId, //审核人Id    ***
                workId: '', //流程Id
            }
            request.undoAudit(params2).then(() => {
                this.clientPop('suc', '撤回成功！', this.handleClose,)
            })
        },

        handleFullScreen () {
            this.fullscreen = !this.fullscreen
        },
        //取消
        handleClose () {
            this.dialogVisible = false
            this.$router.replace('/totalPlan')
        },
        cellClsNm ({ column }) {
            if (column.label === '') {
                return 'fixed-left'
            }
        },

        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },

        //获取计划明细表格的选择项
        planTableSelect (selection) {
            this.planSelect = selection
        },
        //删除物资明细
        deleteEle (row) {
            row.changeType = -1
        },
        // 打开客户端弹窗，调用客户端api
        openApp () {
            window.getPopData = this.getPopData // 向客户端开放全局变量，让客户端在关闭弹窗时回调并传递回数据
            callbackObj.changeLoadingState(true) // ChangeLoadingState为客户端提供打开loading的方法

            // 本地模拟ajax异步，编写业务代码时修改为ajax
            setTimeout(() => {
                callbackObj.changeLoadingState(false) // 调用客户端api关闭loadin
                callbackObj.openWindow('/search') // OpenWindow为客户端提供打开弹窗的方法
            }, 2000)
        },
        // 接收客户端回调数据的方法
        getPopData (msg) {
            // 接收弹窗关闭时的form表单数据，并处理业务逻辑
            alert(`getPopData: ${msg}`)

            window.getPopData = null // 释放全局变量
        },
        //获取当前时间
        geyDate () {
            var myDate = new Date()
            return myDate
        },
    },
}
</script>

<style lang="scss">
.buttons {
  left: 0;
}
.e-form {
  margin-bottom: 80px;
  padding: 0 20px;
  .tabs-title::before {
    content: "";
    height: 22px;
    width: 8px;
    border-radius: 40px;
    background-color: #2e61d7;
    display: block;
    position: absolute;
    left: 20px;
    margin-right: 20px;
  }
}

.e-table {
  background: #fff;
  .totoal {
    margin-left: 10px;
    cursor: pointer;
    color: blue;
  }
}
.el-table .warning-row {
  display: none;
}
// ::v-deep.el-table__body-wrapper::-webkit-scrollbar{
//      width: 6px !important; // 横向滚动条
//     height: 10px !important// 纵向滚动条
// }

::v-deep .el-table__body-wrapper::-webkit-scrollbar {
  width: 6px; // 横向滚动条
  height: 10px; // 纵向滚动条
}
// 滚动条的滑块
::v-deep .el-table__body-wrapper::-webkit-scrollbar-thumb {
  background-color: #ddd;
  border-radius: 5px;
}

.el-tab-pane {
  margin-left: -10px;
}
</style>
